﻿using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using DocumentFormat.OpenXml.ExtendedProperties;
using DocumentFormat.OpenXml.Office2010.Excel;
//using DocumentFormat.OpenXml.Spreadsheet;
using Learun.Application.Base.SystemModule;
using Learun.Cache.Base;
using Learun.Util;
using Learun.Util.SqlSugar;
using log4net.Config;
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using static Learun.Application.TwoDevelopment.ZZDT_EC.ProjectSugar;
using static Learun.Util.SqlSugar.SqlSugarHelper;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-03-07 13:44
    /// 描 述：工程数据表
    /// </summary>
    public class ec_enginedataBLL : ec_enginedataIBLL
    {
        private ec_enginedataService ec_enginedataService = new ec_enginedataService();
        public enum ExportType
        {
            /// <summary>
            /// 
            /// </summary>
            XYZtoS3D = 0
        }
        #region 获取数据
        public byte[] ExportExcel(string projectId, ExportType exportType)
        {
            byte[] RES = null;
            switch (exportType)
            {
                case ExportType.XYZtoS3D:
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using (var package = new ExcelPackage())
                    {
                        //具体逻辑
                        package.Workbook.Worksheets.Add("Equipments");
                        var sheet = package.Workbook.Worksheets[0];
                        sheet.Cells["A1"].Value = "序号";
                        sheet.Cells["B1"].Value = "AMD";
                        sheet.Cells["C1"].Value = "设备位号";
                        sheet.Cells["D1"].Value = "中文名称";
                        sheet.Cells["E1"].Value = "英文名称";
                        sheet.Cells["F1"].Value = "PartNumber";
                        sheet.Cells["G1"].Value = "肋位号";
                        sheet.Cells["H1"].Value = "偏移值X(m)";
                        sheet.Cells["I1"].Value = "偏移值Y(m)";
                        sheet.Cells["J1"].Value = "甲板";
                        sheet.Cells["K1"].Value = "偏移值Z(m)";
                        sheet.Cells["L1"].Value = "房间号";
                        sheet.Cells["M1"].Value = "是否导入";
                        int count = 2;
                        //获取所有位号
                        List<dynamic> lstEngineData = GetEnginedataFor3D(projectId);
                        foreach (var item in lstEngineData)
                        {
                            sheet.Cells["A" + count.ToString()].Value = count - 1;
                            sheet.Cells["C" + count.ToString()].Value = item.TagNumber;
                            sheet.Cells["D" + count.ToString()].Value = item.ChineseName;
                            sheet.Cells["E" + count.ToString()].Value = item.EnglishName;
                            sheet.Cells["F" + count.ToString()].Value = item.PartNumber;
                            sheet.Cells["G" + count.ToString()].Value = item.RibNumber;
                            if(!string.IsNullOrEmpty(item.XOffset))
                            {
                                sheet.Cells["H" + count.ToString()].Value = Math.Round(double.Parse(item.XOffset)/1000,2);
                            }
                            if (!string.IsNullOrEmpty(item.YOffset))
                            {
                                sheet.Cells["I" + count.ToString()].Value = Math.Round(double.Parse(item.YOffset) / 1000,2);
                            }
                            sheet.Cells["J" + count.ToString()].Value = item.DeckNumber;
                            if (!string.IsNullOrEmpty(item.GroundHeight))
                            {
                                sheet.Cells["k" + count.ToString()].Value = Math.Round(double.Parse(item.GroundHeight) / 1000, 2);
                            }
                            sheet.Cells["L" + count.ToString()].Value = item.RoomNumber;
                            count++;
                        }
                        RES = package.GetAsByteArray();
                    } 
                    break;
                default:
                    break;
            }
            return RES;
        }
        /// <summary>
        /// 抽取S3D需要的2D数据
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <returns>LIST清单</returns>
        public List<dynamic> GetEnginedataFor3D(string projectId)
        {
            try
            {
                var enginedataTableName = TableName<ec_enginedataEntity>(projectId);
                var propertyTableName=TableName<ec_enginedata_propertyEntity>(projectId);
                var typeTableName = TableName<ec_objecttypeEntity>(projectId);
                var pixelTableName = TableName<ec_enginedata_pixelEntity>(projectId);
                var drawingfileTableName = TableName<ec_drawing_fileEntity>(projectId);
                var dataitemdetailTableName = TableName<ec_dataitemdetailEntity>(projectId);

                // 内部子查询：获取有效的EngineDataID
                var validEngineDataIds = Db.Queryable<ec_enginedata_pixelEntity>()
                    .AS(pixelTableName)
                    .LeftJoin<ec_drawing_fileEntity>((edp, edf) => edp.DrawingFileID == edf.DrawingFileID)
                    .AS<ec_drawing_fileEntity>(drawingfileTableName)
                    .LeftJoin<ec_dataitemdetailEntity>((edp, edf, did) => edf.DrawingType == did.DataItemDetailID)
                    .AS<ec_dataitemdetailEntity>(dataitemdetailTableName)
                    .Where((edp, edf, did) => did.DataItemName == "布置图")
                    .Select(edp => edp.EngineDataID)
                    .Distinct()
                    .ToList();

                var result = Db.Queryable<ec_enginedataEntity>()
                    .AS(enginedataTableName)
                    .LeftJoin<ec_enginedata_propertyEntity>((ed, edp) => ed.EngineDataID == edp.EngineDataID)
                    .AS<ec_enginedata_propertyEntity>(propertyTableName)
                    .LeftJoin<ec_objecttypeEntity>((ed, edp, eo) => ed.ObjectTypeID == eo.ObjectTypeID)
                    .AS<ec_objecttypeEntity>(typeTableName)
                    .Where((ed, edp, eo) =>
                        eo.ObjectTypeName != "电缆" &&
                        edp.CaseID == "0" &&
                        validEngineDataIds.Contains(ed.EngineDataID)
                    )
                    .Select((ed, edp, eo) => new
                    {
                        ed.TagNumber,
                        edp.PropertyName,
                        edp.PropertyValue
                    })
                    .ToList()
                    .GroupBy(x => x.TagNumber)
                    .Select(g => new
                    {
                        TagNumber = g.Key,
                        ChineseName = g.Max(x => x.PropertyName == "中文名称" ? x.PropertyValue : null),
                        EnglishName = g.Max(x => x.PropertyName == "英文名称" ? x.PropertyValue : null),
                        PartNumber = g.Max(x => x.PropertyName == "Part Number" ? x.PropertyValue : null),
                        RibNumber = g.Max(x => x.PropertyName == "肋位号" ? x.PropertyValue : null),
                        XOffset = g.Max(x => x.PropertyName == "肋位号偏移量(mm)" ? x.PropertyValue : null),
                        YOffset = g.Max(x => x.PropertyName == "纵骨偏移量(mm)" ? x.PropertyValue : null),
                        DeckNumber = g.Max(x => x.PropertyName == "甲板号" ? x.PropertyValue : null),
                        GroundHeight = g.Max(x => x.PropertyName == "离地高度(mm)" ? x.PropertyValue : null),
                        RoomNumber = g.Max(x => x.PropertyName == "房间号" ? x.PropertyValue : null)
                    })
                    .ToList<dynamic>();

                return result;
            }
            catch (Exception)
            {
                return null;
                throw;
            }
        }
        /// <summary>
        /// 获取回收站页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        public IEnumerable<ec_enginedataEntity> GetRecycleBinPageList(Pagination pagination, string queryJson)
        {
            try
            {
                return ec_enginedataService.GetRecycleBinPageList(pagination, queryJson);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 根据where查询数据（BY YuXH）
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        public IEnumerable<ec_enginedataEntity> GetListBySQL(string queryJson, string projId)
        {
            try
            {
                return ec_enginedataService.GetListBySQL(queryJson, projId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }


        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <paramref name="DataFromWeb">是否来自网页查询</paramref>
        /// <returns></returns>
        public IEnumerable<ec_enginedataEntity> GetList(string queryJson, Pagination pagination = null, bool Distinct = true, bool DataFromWeb = false)
        {
            try
            {
                var queryParam = queryJson.ToJObject();
                var ProjectId = queryParam["ProjectId"]?.ToString();
                var TagNumber = queryParam["TagNumber"]?.ToString();
                var ObjectTypeID = queryParam["ObjectTypeID"]?.ToString();
                var DataStatus = queryParam["DataStatus"]?.ToString();
                var NotEngineDataID = queryParam["NotEngineDataID"]?.ToString();
                var ObjectTypeIDs = queryParam["ObjectTypeIDs"]?.ToString();
                var TagNumbers = queryParam["TagNumbers"]?.ToString();
                var TagNumberFilter = queryParam["TagNumberFilter"]?.ToString();
                var EngineDataID = queryParam["EngineDataID"]?.ToString();

                var DrawingFileID = queryParam["DrawingFileID"]?.ToString();
                var PixelCode = queryParam["PixelCode"]?.ToString();
                var PixelCodes = queryParam["PixelCodes"]?.ToString();

                var UpObjectTypeID = queryParam["UpObjectTypeID"]?.ToString();
                var FullPath = queryParam["FullPath"]?.ToString();
                var system = queryParam["system"]?.ToString(); //所属系统
                var tableName = TableName<ec_enginedataEntity>(ProjectId);
                var pixelTableName = TableName<ec_enginedata_pixelEntity>(ProjectId);
                var typeTableName = TableName<ec_objecttypeEntity>(ProjectId);
                var opcTableName = TableName<ec_OPCEntity>(ProjectId);
                ISugarQueryable<ec_enginedataEntity> query;

                if (Distinct)
                {
                    query = Db.Queryable<ec_enginedataEntity>().AS(tableName)
                                        .WhereIF(!string.IsNullOrEmpty(TagNumber) && DataFromWeb.Equals(false), x => x.TagNumber == TagNumber)
                                        .WhereIF(!string.IsNullOrEmpty(TagNumber) && DataFromWeb.Equals(true), x => x.TagNumber.Contains(TagNumber))
                                        .WhereIF(!string.IsNullOrEmpty(ObjectTypeID), x => x.ObjectTypeID == ObjectTypeID)
                                        .WhereIF(!string.IsNullOrEmpty(DataStatus), x => x.DataStatus == DataStatus)
                                        .WhereIF(!string.IsNullOrEmpty(NotEngineDataID), x => x.EngineDataID != NotEngineDataID)
                                        .WhereIF(!string.IsNullOrEmpty(ObjectTypeIDs), x => SqlFunc.SplitIn(ObjectTypeIDs, x.ObjectTypeID))
                                        .WhereIF(!string.IsNullOrEmpty(TagNumbers), x => SqlFunc.SplitIn(TagNumbers, x.TagNumber))
                                        .WhereIF(!string.IsNullOrEmpty(TagNumberFilter), x => x.TagNumber.Contains(TagNumberFilter))
                                        .WhereIF(!string.IsNullOrEmpty(EngineDataID), x => x.EngineDataID == EngineDataID)
                                        .WhereIF(!string.IsNullOrEmpty(DrawingFileID) && (!string.IsNullOrEmpty(PixelCode) || !string.IsNullOrEmpty(PixelCodes)),
                                        x => x.EngineDataID == SqlFunc.Subqueryable<ec_enginedata_pixelEntity>().AS(pixelTableName).Where(y => y.DrawingFileID == DrawingFileID)
                                            .WhereIF(!string.IsNullOrEmpty(PixelCode), y => y.PixelCode == PixelCode)
                                            .WhereIF(!string.IsNullOrEmpty(PixelCodes), y => SqlFunc.SplitIn(PixelCodes, y.PixelCode))
                                            .GroupBy(y => y.EngineDataID).Select(y => y.EngineDataID)
                                            )
                                        .WhereIF(!string.IsNullOrEmpty(UpObjectTypeID),
                                        x => x.ObjectTypeID == SqlFunc.Subqueryable<ec_objecttypeEntity>().AS(typeTableName).Where(y => y.FullPath.Contains(UpObjectTypeID)).GroupBy(y => y.ObjectTypeID).Select(y => y.ObjectTypeID)
                                            )
                                        .WhereIF(!string.IsNullOrEmpty(FullPath),
                                        x => x.ObjectTypeID == SqlFunc.Subqueryable<ec_objecttypeEntity>().AS(typeTableName).Where(y => y.FullPath.Contains(FullPath)).GroupBy(y => y.ObjectTypeID).Select(y => y.ObjectTypeID)
                                        )
                                        .OrderByDescending(x => x.CreateTime);
                }
                else
                {
                    //相当于每一个pixel都需要对应一个Enginedata
                    query = Db.Queryable<ec_enginedataEntity>().AS(tableName).
                         RightJoin<ec_enginedata_pixelEntity>((A, B) => A.EngineDataID == B.EngineDataID).AS<ec_enginedata_pixelEntity>(pixelTableName).
                         Where((A, B) => PixelCodes.Contains(B.PixelCode)).
                         WhereIF(!string.IsNullOrEmpty(TagNumber), x => x.TagNumber == TagNumber)
                                        .WhereIF(!string.IsNullOrEmpty(ObjectTypeID), x => x.ObjectTypeID == ObjectTypeID)
                                        .WhereIF(!string.IsNullOrEmpty(DataStatus), x => x.DataStatus == DataStatus)
                                        .WhereIF(!string.IsNullOrEmpty(NotEngineDataID), x => x.EngineDataID != NotEngineDataID)
                                        .WhereIF(!string.IsNullOrEmpty(ObjectTypeIDs), x => SqlFunc.SplitIn(ObjectTypeIDs, x.ObjectTypeID))
                                        .WhereIF(!string.IsNullOrEmpty(TagNumbers), x => SqlFunc.SplitIn(TagNumbers, x.TagNumber))
                                        .WhereIF(!string.IsNullOrEmpty(TagNumberFilter), x => x.TagNumber.Contains(TagNumberFilter))
                                        .WhereIF(!string.IsNullOrEmpty(EngineDataID), x => x.EngineDataID == EngineDataID)
                         .WhereIF(!string.IsNullOrEmpty(DrawingFileID), (A, B) => B.DrawingFileID == DrawingFileID)
                     .WhereIF(!string.IsNullOrEmpty(UpObjectTypeID),
                                        x => x.ObjectTypeID == SqlFunc.Subqueryable<ec_objecttypeEntity>().AS(typeTableName).Where(y => y.FullPath.Contains(UpObjectTypeID)).GroupBy(y => y.ObjectTypeID).Select(y => y.ObjectTypeID)
                                            )
                                        .WhereIF(!string.IsNullOrEmpty(FullPath),
                                        x => x.ObjectTypeID == SqlFunc.Subqueryable<ec_objecttypeEntity>().AS(typeTableName).Where(y => y.FullPath.Contains(FullPath)).GroupBy(y => y.ObjectTypeID).Select(y => y.ObjectTypeID)
                                        );
                }

                List<ec_enginedataEntity> list;
                if (pagination == null)
                {
                    list = query.ToList();
                }
                else
                {
                    int totalNumber = 0;
                    int totalPage = 0;
                    list = query.ToPageList(pagination.page, pagination.rows, ref totalNumber, ref totalPage);
                    pagination.records = totalNumber;
                    pagination.total = totalPage;
                }
                var allOPCs = Db.Queryable<ec_OPCEntity>().AS(opcTableName).ToList();
                var typeIds = new List<string>();
                list?.ForEach(x =>
                {
                    typeIds.Add(x.ObjectTypeID);
                });

                if (!string.IsNullOrEmpty(system))
                {
                    var propTableName = TableName<ec_enginedata_propertyEntity>(ProjectId);
                    ;

                    var tagsWithRightSystem = Db.Queryable<ec_enginedata_propertyEntity>().AS(propTableName)
                        .Where(x => x.PropertyName == GlobalObject.propName_System && x.CaseID == "0" && x.PropertyValue == system)
                        .Where(x => list.Select(y => y.EngineDataID).Contains(x.EngineDataID))
                        .ToList();

                    list = list.Where(x => tagsWithRightSystem.Select(y => y.EngineDataID).Contains(x.EngineDataID))
                        .ToList();
                }
                var temp = Db.Queryable<ec_objecttypeEntity>().AS(typeTableName).First(x => x.ObjectTypeID == "88d7ead3-8872-434b-b623-dbb42d054215");
                var types = Db.Queryable<ec_objecttypeEntity>().AS(typeTableName).Where(x => typeIds.Contains(x.ObjectTypeID)).ToList();
                var details = Db.Queryable<DataItemDetailEntity>()
                    .InnerJoin<DataItemEntity>((a, b) => a.F_ItemId == b.F_ItemId && b.F_ItemCode == "Be_DataStatus").ToList();
                list?.ForEach(x =>
                {
                    if (allOPCs.Any(opc => opc.OPCID == x.EngineDataID))
                    {
                        x.ObjectTypeID = "OPC";
                        x.ObjectTypeName = "OPC";
                        x.ObjectTypeNameEN = "OPC";
                        x.FullPathCN = "OPC";
                        x.DataStatusName = "";
                        x.TagNumber = allOPCs.FirstOrDefault(opc => opc.OPCID == x.EngineDataID)?.OPCTAG;
                    }
                    else
                    {
                        x.ObjectTypeName = types.FirstOrDefault(y => y.ObjectTypeID == x.ObjectTypeID)?.ObjectTypeName;
                        x.FullPathCN = types.FirstOrDefault(y => y.ObjectTypeID == x.ObjectTypeID)?.FullPathCN;
                        x.DataStatusName = details.FirstOrDefault(y => y.F_ItemValue == x.DataStatus)?.F_ItemName;
                    }

                });
                //平行电缆
                var pServ = new ec_parallel_CableService();
                var parallels = list.Where(x => x.ObjectTypeName?.EndsWith("电缆") == true).ToList();
                if (parallels != null && parallels.Count > 0)
                {
                    //var engineDataIDs = string.Join(",", parallels.Select(x => x.EngineDataID));//2023 07 30,这里数量太多感觉是有点问题的，能不能不用string去划分
                    var parallel_cables = pServ.GetList(ProjectId, parallels.Select(x => x.EngineDataID).ToList());
                    parallels.ForEach(x =>
                    {
                        x.parallel_cables = parallel_cables.Where(y => y.engineerDataId == x.EngineDataID).ToList();
                    });
                }
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        public IEnumerable<ec_enginedataEntity> GetListByDrawing(string ProjectId, string dwgFileId)
        {
            var tableName = TableName<ec_enginedataEntity>(ProjectId);
            var pixelTableName = TableName<ec_enginedata_pixelEntity>(ProjectId);
            var typeName = TableName<ec_objecttypeEntity>(ProjectId);
            var allTagIdsOnDwg = Db.Queryable<ec_enginedata_pixelEntity>().AS(pixelTableName).
                    Where(x => x.DrawingFileID == dwgFileId).
                    Select(x => x.EngineDataID).
                    Distinct().
                    ToList();
            var allTypes = Db.Queryable<ec_objecttypeEntity>().AS(pixelTableName).ToList();
            var res = Db.Queryable<ec_enginedataEntity>().AS(tableName).
                Where(x => allTagIdsOnDwg.Contains(x.EngineDataID)).ToList();
            foreach (var tag in res)
            {
                tag.ObjectTypeName = allTypes.FirstOrDefault(x => x.ObjectTypeID == tag.ObjectTypeID)?.ObjectTypeName;
            }
            return res;
        }

        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <paramref name="DataFromWeb">是否来自网页查询</paramref>
        /// <returns></returns>
        public IEnumerable<ec_enginedataEntity> GetListByPixel(string ProjectId, string dwgFileId, string pixelCodes)
        {
            try
            {
                var tableName = TableName<ec_enginedataEntity>(ProjectId);
                var pixelTableName = TableName<ec_enginedata_pixelEntity>(ProjectId);
                var typeTableName = TableName<ec_objecttypeEntity>(ProjectId);
                var opcTableName = TableName<ec_OPCEntity>(ProjectId);

                var pixelList = pixelCodes.Split(',');
                var allPixels = Db.Queryable<ec_enginedata_pixelEntity>().AS(pixelTableName).
                    Where(x => pixelList.Contains(x.PixelCode) && x.DrawingFileID == dwgFileId && x.DeleteFlg != 1).ToList();


                List<ec_enginedataEntity> list = new List<ec_enginedataEntity>();
                var allOPCs = Db.Queryable<ec_OPCEntity>().AS(opcTableName).ToList();
                var types = Db.Queryable<ec_objecttypeEntity>().AS(typeTableName).ToList();
                var allTags = Db.Queryable<ec_enginedataEntity>().AS(tableName).ToList();
                var details = Db.Queryable<DataItemDetailEntity>()
                    .InnerJoin<DataItemEntity>((a, b) => a.F_ItemId == b.F_ItemId && b.F_ItemCode == "Be_DataStatus").ToList();


                foreach (var pixel in pixelList)
                {
                    var pixelObj = allPixels.FirstOrDefault(x => x.PixelCode == pixel);
                    if (pixelObj != null)
                    {

                        var tag = allTags.FirstOrDefault(x => x.EngineDataID == pixelObj.EngineDataID);
                        if (tag != null)
                        {
                            if (pixelObj.RepresentationType == "OPC")
                            {
                                tag.ObjectTypeID = "OPC";
                                tag.ObjectTypeName = "OPC";
                                tag.ObjectTypeNameEN = "OPC";
                                tag.FullPathCN = "OPC";
                                tag.DataStatusName = "";
                                tag.TagNumber = allOPCs.FirstOrDefault(opc => opc.OPCID == tag.EngineDataID)?.OPCTAG;
                            }
                            else
                            {
                                tag.ObjectTypeName = types.FirstOrDefault(y => y.ObjectTypeID == tag.ObjectTypeID)?.ObjectTypeName;
                                tag.ObjectTypeNameEN = types.FirstOrDefault(y => y.ObjectTypeID == tag.ObjectTypeID)?.ObjectTypeNameEN;
                                tag.FullPathCN = types.FirstOrDefault(y => y.ObjectTypeID == tag.ObjectTypeID)?.FullPathCN;
                                tag.DataStatusName = details.FirstOrDefault(y => y.F_ItemValue == tag.DataStatus)?.F_ItemName;
                            }

                            list.Add(tag);
                        }



                    }
                }



                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }



        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_enginedataEntity GetEntity(string keyValue, string ProjectId)
        {
            try
            {
                return ec_enginedataService.GetEntity(keyValue, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 获取记录条数
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public int GetDataCount(string ProjectId)
        {
            try
            {
                return ec_enginedataService.GetDataCount(ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, string ProjectId)
        {
            try
            {
                ec_enginedataService.DeleteEntity(keyValue, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_enginedataEntity entity, string ProjectId)
        {
            try
            {
                ec_enginedataService.SaveEntity(keyValue, entity, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 批量保存导入的工程数据、属性(更新的case为0）
        /// <summary>
        /// <returns></returns>
        public void SaveImportData(List<ec_enginedataEntity> entityList, string ProjectId)
        {
            try
            {
                ec_enginedataService.SaveImportData(entityList, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 批量修改数据状态
        /// <summary>
        /// <returns></returns>
        public void UpdateDataStatus(List<ec_enginedataEntity> entityList, string ProjectId)
        {
            try
            {
                ec_enginedataService.UpdateDataStatus(entityList, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 对象浏览器修改位号
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="oldTagNumber">修改前位号</param>
        /// <param name="newTagNumber">修改后位号</param>
        /// <param name="isCover">是否覆盖:覆盖 1，不覆盖 0</param>
        /// <returns></returns>
        public void RenameTagNumber(string projectId, string oldTagNumber, string newTagNumber, string isCover)
        {
            try
            {
                string delEngineDataID = string.Empty;//要删除的工程数据ID
                List<ec_enginedata_propertyEntity> updataEngineDataProp = new List<ec_enginedata_propertyEntity>();//要更新的工程数据属性集合
                List<ec_enginedata_propertyEntity> addEngineDataProp = new List<ec_enginedata_propertyEntity>();//要新增的工程数据属性集合
                List<ec_enginedata_pixelEntity> updataEngineDataPixel = new List<ec_enginedata_pixelEntity>();//要更新的工程数据图元集合
                List<ec_enginedata_propertyhisEntity> engineDataPropHis = new List<ec_enginedata_propertyhisEntity>();//要新增的工程数据属性历史数据集合
                UserInfo userInfo = LoginUserInfo.Get();
                string curUserID = userInfo.userId;
                var newEngineData = GetList("{\"ProjectId\":\"" + projectId + "\",\"TagNumber\":\"" + newTagNumber + "\" }").FirstOrDefault();//A0001
                var oldEngineData = GetList("{\"ProjectId\":\"" + projectId + "\",\"TagNumber\":\"" + oldTagNumber + "\" }").FirstOrDefault();//A0009
                if (newEngineData != null)
                {//如果修改后的位号在工程数据表中存在,修改工程数据图元表的工程数据ID为修改后的工程数据ID
                    delEngineDataID = oldEngineData.EngineDataID;
                    updataEngineDataPixel = new ec_enginedata_pixelService().GetEnginePixelById(projectId, oldEngineData.EngineDataID).ToList();
                    updataEngineDataPixel = updataEngineDataPixel.Select(x => { x.EngineDataID = newEngineData.EngineDataID; x.UpdateTime = DateTime.Now; x.UpdateUserID = userInfo.userId; return x; }).
                        Where(x => !string.IsNullOrEmpty(x.EngineDataPixelID)).ToList();
                    //覆盖：覆盖当前位号的工程数据属性表，删除工程数据表数据,不覆盖：删除当前位号的工程数据属性表、工程数据表数据
                    if (isCover == "1")
                    {
                        var oldEngineDataProperty = new ec_enginedata_propertyService().GetTagPropById(projectId, oldEngineData.EngineDataID, "0").ToList();
                        var newEngineDataProperty = new ec_enginedata_propertyService().GetTagPropById(projectId, newEngineData.EngineDataID, "0").ToList();
                        foreach (var item in oldEngineDataProperty)
                        {
                            var tempData = newEngineDataProperty.Find(x => x.PropertyName == item.PropertyName);
                            if (tempData != null)
                            {
                                if (!string.IsNullOrEmpty(item.PropertyValue) || (!string.IsNullOrEmpty(item.MeasuringUnit) && tempData?.MeasuringUnit != item.MeasuringUnit))
                                {
                                    ec_enginedata_propertyhisEntity modelHis = new ec_enginedata_propertyhisEntity();
                                    modelHis.EngineDataID = tempData.EngineDataID;
                                    modelHis.PropertyName = tempData.PropertyName;
                                    modelHis.PropertyValue = tempData.PropertyValue;

                                    //更新属性时需要设置工程数据属性表的更新人、更新时间，同时，插入工程数据属性历史表。
                                    if (string.IsNullOrWhiteSpace(tempData?.CreateUserID) && tempData?.CreateTime == null)
                                    {
                                        tempData.CreateTime = Time.MySqlTime;
                                        tempData.CreateUserID = curUserID;
                                    }
                                    tempData.Modify(tempData.EngineDataPropertyID);
                                    if (!string.IsNullOrEmpty(item.PropertyValue))
                                    {
                                        tempData.PropertyValue = item.PropertyValue;
                                    }
                                    tempData.MeasuringUnit = item.MeasuringUnit;
                                    updataEngineDataProp.Add(tempData);

                                    if (!string.IsNullOrEmpty(item.PropertyValue))
                                    {
                                        modelHis.Create();
                                        engineDataPropHis.Add(modelHis);
                                    }
                                }
                            }
                            else
                            {
                                item.Create();
                                item.EngineDataID = newEngineData.EngineDataID;
                                addEngineDataProp.Add(item);
                            }
                        }
                    }
                }
                else
                {//如果修改后的位号在工程数据表中不存在，修改当前位号为修改后的位号。
                    oldEngineData.TagNumber = newTagNumber;
                    oldEngineData.UpdateTime = Time.MySqlTime;
                    oldEngineData.UpdateUserID = userInfo.userId;

                    // 记录
                    ec_operate_logEntity entityLog = new ec_operate_logEntity();
                    entityLog.OwnerID = oldEngineData.EngineDataID;
                    entityLog.OperateType = "重命名（不存在的）";
                    entityLog.FileVersion = "0";
                    entityLog.Create();

                    new ec_operate_logService().SaveEntity("", entityLog, projectId);
                }
                ec_enginedataService.UpdateTagNumber(projectId, oldEngineData, delEngineDataID, updataEngineDataPixel, updataEngineDataProp, addEngineDataProp, engineDataPropHis);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 图元属性修改。包括新建位号
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="entity">工程数据实体</param>
        /// <param name="caseID">工程数据实体</param>
        public void UpdatePixelAndProp(string projectId, ec_enginedataEntity entity)
        {
            var caseID = entity.CaseID;
            var ec_relDataBLL = new ec_enginedata_relBLL();
            Db.BeginTran();
            try
            {
                var ProjectEntity = Db.Queryable<ec_projectEntity>().Single(x => x.ProjectId == projectId);
                var caseTableName = TableName<ec_CaseEntity>(ProjectEntity.ProjectIndex.ToString());
                var propertyTableName = TableName<ec_propertyEntity>(ProjectEntity.ProjectIndex.ToString());
                var objectTypeTableName = TableName<ec_objecttypeEntity>(ProjectEntity.ProjectIndex.ToString());
                var objectTypepTableName = TableName<ec_objecttypepEntity>(ProjectEntity.ProjectIndex.ToString());
                var unitTableName = TableName<ec_measuring_unitEntity>(ProjectEntity.ProjectIndex.ToString());


                if (entity.ObjectTypeID == "OPC")
                {
                    var OPCId = "";
                    #region OPC

                    //和开关一样（不完全一样，开关不会有自己的pixel记录），只有在自己的表里有，不会在ec_enginedata表里出现
                    var opcBll = new ec_OPCBLL();
                    var opcs = opcBll.GetList(projectId);
                    var curOPC = opcs.FirstOrDefault(x => x.OPCTAG == entity.TagNumber);
                    if (curOPC != null)
                    {
                        //修改
                        OPCId = curOPC.OPCID;
                        curOPC.Modify(curOPC.OPCID);
                        foreach (var engineDataProp in entity.EngineDataProperty)
                        {
                            switch (engineDataProp.PropertyName)
                            {
                                case "用途":
                                    curOPC.DESC = engineDataProp.PropertyValue;
                                    break;
                                case "From信息":
                                    curOPC.FROMTEXT = engineDataProp.PropertyValue;
                                    break;
                                case "To信息":
                                    curOPC.TOTEXT = engineDataProp.PropertyValue;
                                    break;
                                default:
                                    break;
                            }
                        }

                        Db.Updateable(curOPC).AS($"ec_OPC_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                    else
                    {
                        //插入
                        if (string.IsNullOrEmpty(entity.EngineDataID))
                        {
                            var newOPC = new ec_OPCEntity()
                            {

                            };
                            newOPC.Create();//ID生成
                            newOPC.OPCTAG = entity.TagNumber;
                            OPCId = newOPC.OPCID;
                            foreach (var engineDataProp in entity.EngineDataProperty)
                            {
                                switch (engineDataProp.PropertyName)
                                {
                                    case "用途":
                                        newOPC.DESC = engineDataProp.PropertyValue;
                                        break;
                                    case "From信息":
                                        newOPC.FROMTEXT = engineDataProp.PropertyValue;
                                        break;
                                    case "To信息":
                                        newOPC.TOTEXT = engineDataProp.PropertyValue;
                                        break;
                                    default:
                                        break;
                                }
                            }


                            ec_enginedataEntity newOPCEnginedata = new ec_enginedataEntity();
                            newOPCEnginedata.EngineDataID = newOPC.OPCID;
                            newOPCEnginedata.ObjectTypeID = "OPC";
                            newOPCEnginedata.TagNumber = newOPC.OPCTAG;

                            //同时工程表也插入一下
                            Db.Insertable(newOPCEnginedata).AS($"ec_enginedata_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                            Db.Insertable(newOPC).AS($"ec_OPC_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        }


                    }
                    #endregion


                    #region 根据传过来的图元集合
                    if (entity.EngineDataPixel == null)
                    {
                        entity.EngineDataPixel = new List<ec_enginedata_pixelEntity>();
                    }
                    foreach (var pixel in entity.EngineDataPixel)//修改时选中的那个pixel
                    {
                        var existPixel = Db.Queryable<ec_enginedata_pixelEntity>().AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").
                            First(x => x.DrawingFileID == pixel.DrawingFileID && x.PixelCode == pixel.PixelCode);
                        if (existPixel != null)
                        {
                            existPixel.Modify(existPixel.EngineDataPixelID);
                            existPixel.DeleteFlg = 0;
                            existPixel.EngineDataID = OPCId;
                            existPixel.LibraryFileID = pixel.LibraryFileID;
                            existPixel.MaxPointX = pixel.MaxPointX;
                            existPixel.MinPointX = pixel.MinPointX;
                            existPixel.MaxPointY = pixel.MaxPointY;
                            existPixel.MinPointY = pixel.MinPointY;
                            existPixel.RepresentationType = "OPC";
                            Db.Updateable(existPixel).AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        }
                        else
                        {
                            var existPixels = Db.Queryable<ec_enginedata_pixelEntity>().AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").
                        Where(x => x.EngineDataID == OPCId).ToList();
                            if (existPixels != null)
                            {
                                if (existPixels.Count < 2)
                                {
                                    pixel.Create();
                                    pixel.DeleteFlg = 0;
                                    pixel.EngineDataID = OPCId;
                                    pixel.RepresentationType = "OPC";
                                    Db.Insertable(pixel).AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                                }
                                else
                                {
                                    //无法超过2个
                                }
                            }
                            else
                            {
                                //0个
                                pixel.Create();
                                pixel.DeleteFlg = 0;
                                pixel.EngineDataID = OPCId;
                                Db.Insertable(pixel).AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                            }

                        }
                        //SqlSugarHelper.Db.Ado.ExecuteCommand($" DELETE FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} WHERE DrawingFileID = '{pixel.DrawingFileID}' AND PixelCode = '{pixel.PixelCode}';");

                    }

                    //db.InsertByNoMap(entity.EngineDataPixel, $"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}");

                    #endregion
                }
                else
                {
                    var curEnginedata = GetList(("{\"ProjectId\":\"" + projectId + "\",\"TagNumber\":\"" + entity.TagNumber + "\"}")).FirstOrDefault();

                    string engineDataID = "";

                    #region case无效就退出
                    var cases = Db.Queryable<ec_CaseEntity>().AS(caseTableName).ToList();
                    if (string.IsNullOrEmpty(caseID))
                    {
                        caseID = "0";
                    }
                    if (!cases.Any(X => X.CaseID == caseID)) throw new Exception("无效的CaseId");
                    #endregion
                    //1、位号不存在时，新增位号记录，位号存在时，更新对象类型。
                    if (curEnginedata != null)
                    {
                        #region  修改
                        curEnginedata.Modify(curEnginedata.EngineDataID);
                        curEnginedata.ObjectTypeID = entity.ObjectTypeID;

                        //2、删除工程数据属性表再插入。
                        //db.ExecuteBySql($" DELETE FROM ec_enginedata_property_{ ProjectEntity.ProjectIndex} WHERE EngineDataID = '{curEnginedata.EngineDataID}' ");

                        UserInfo userInfo = LoginUserInfo.Get();
                        string curUserID = userInfo.userId;
                        //需要新增的工程数据属性数据
                        List<ec_enginedata_propertyEntity> engineDataPropInsert = new List<ec_enginedata_propertyEntity>();
                        //需要更新的工程数据属性数据，并且需要插入工程数据属性历史表
                        List<ec_enginedata_propertyEntity> engineDataPropUpdate = new List<ec_enginedata_propertyEntity>();
                        List<ec_enginedata_propertyhisEntity> engineDataPropHis = new List<ec_enginedata_propertyhisEntity>();
                        //获取当前工程数据下面的属性
                        var allEngineProp = new ec_enginedata_propertyService().GetTagPropById(projectId, curEnginedata.EngineDataID, caseID).ToList();
                        foreach (var prop in entity.EngineDataProperty.Where(x => x.PropertyName != "HKSK_POSITION_NUM"))
                        {
                            ec_enginedata_propertyEntity tempModel;
                            if (string.IsNullOrEmpty(caseID))
                            {
                                prop.CaseID = "0";
                                //如果某个工况的某个属性在数据库里么有，干脆直接加一个
                                tempModel = allEngineProp.Find(x => x.PropertyName == prop.PropertyName
                                && (x.CaseID == "0" || string.IsNullOrEmpty(x.CaseID)));//免得重复
                            }
                            else
                            {
                                prop.CaseID = caseID;
                                tempModel = allEngineProp.Find(x => x.PropertyName == prop.PropertyName
                                && (x.CaseID == caseID));//免得重复
                            }



                            //判断传过来的属性是否在数据库已经存在
                            if (tempModel == null)
                            {//新增属性时需要设置工程数据属性表的创建人、创建时间
                             //if (!string.IsNullOrEmpty(prop.PropertyValue))
                             //{//新增时没有属性值的不需要保存
                                prop.Create();
                                prop.EngineDataID = curEnginedata.EngineDataID;
                                //prop.CaseID = caseID;
                                engineDataPropInsert.Add(prop);
                                //}
                            }
                            else
                            {
                                //更新时需要判断属性值是否有修改
                                if (tempModel?.PropertyValue != prop.PropertyValue || tempModel?.MeasuringUnit != prop.MeasuringUnit)
                                {//更新属性时需要设置工程数据属性表的更新人、更新时间，同时，插入工程数据属性历史表。
                                    if (string.IsNullOrWhiteSpace(tempModel?.CreateUserID) && tempModel?.CreateTime == null)
                                    {
                                        prop.CreateTime = Time.MySqlTime;
                                        prop.CreateUserID = curUserID;
                                    }
                                    prop.Modify(tempModel.EngineDataPropertyID);
                                    prop.EngineDataID = curEnginedata.EngineDataID;
                                    engineDataPropUpdate.Add(prop);

                                    if (tempModel?.PropertyValue != prop.PropertyValue)
                                    {
                                        ec_enginedata_propertyhisEntity modelHis = new ec_enginedata_propertyhisEntity();
                                        modelHis.Create();
                                        modelHis.EngineDataID = prop.EngineDataID;
                                        modelHis.PropertyName = prop.PropertyName;
                                        modelHis.PropertyValue = tempModel?.PropertyValue;
                                        modelHis.CaseID = prop.CaseID;
                                        engineDataPropHis.Add(modelHis);
                                    }
                                }

                                //24 03 19,同步电缆规格
                                if (prop.PropertyName == "电缆规格")
                                {
                                    SyncCableSpec(projectId, curEnginedata.EngineDataID, prop.PropertyValue, tempModel.PropertyValue);
                                }
                            }
                        }

                        Db.Insertable(engineDataPropInsert).AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        Db.Updateable(engineDataPropUpdate).AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        Db.Insertable(engineDataPropHis).AS($"ec_enginedata_propertyhis_{ProjectEntity.ProjectIndex}").ExecuteCommand();

                        if (entity.EngineDataPixel != null && entity.EngineDataPixel.Count > 0)
                        {
                            //工程数据图元表有数据时，数据状态更新为待验证区
                            //没必要，只有新增的电气设备才需要变待验证（By YuXH）
                            //    curEnginedata.DataStatus = "00002";
                            XmlConfigurator.Configure();
                            var log = log4net.LogManager.GetLogger("Info"); //参数就是config里logger节点的名字
                            log.Info($"UpdatePixelAndProp,请求Body里，位号{entity.TagNumber}共有{entity.EngineDataPixel.Count}个图元记录。");
                        }
                        //db.UpdateByNoMap(curEnginedata, $"ec_enginedata_{ProjectEntity.ProjectIndex}", "EngineDataID");
                        Db.Updateable(entity).AS($"ec_enginedata_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        engineDataID = curEnginedata.EngineDataID;

                        #endregion
                    }
                    else
                    {
                        #region 插入位号本体
                        ec_enginedataEntity addEnginedata = new ec_enginedataEntity();
                        addEnginedata.Create();
                        addEnginedata.ObjectTypeID = entity.ObjectTypeID;
                        addEnginedata.TagNumber = entity.TagNumber;
                        if (entity.EngineDataPixel != null && entity.EngineDataPixel.Count > 0)
                        {//工程数据图元表有数据时，数据状态更新为待验证区
                            addEnginedata.DataStatus = "00002";
                        }

                        //获取对象类型数据  用来判断是否需要记录流水号
                        var ObjectTypeData = new ec_objecttypeService().GetEntity(addEnginedata.ObjectTypeID, projectId);
                        if (ObjectTypeData?.IsSerialNumber == 1)
                        {
                            //截取位号后面的数字作为流水号
                            if (!string.IsNullOrEmpty(ObjectTypeData.ObjectTypeNameEN))
                            {
                                string strSerialNumber = addEnginedata.TagNumber.Replace(ObjectTypeData.ObjectTypeNameEN, "").Trim();
                                if (IsInteger(strSerialNumber))
                                {
                                    addEnginedata.SerialNumber = strSerialNumber.ToInt();
                                }
                                else
                                {
                                    addEnginedata.SerialNumber = 0;
                                }
                            }
                        }
                        Db.Insertable(addEnginedata).AS($"ec_enginedata_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        engineDataID = addEnginedata.EngineDataID;
                        #endregion


                        #region 新增属性(当前的这套case，值从前端来）
                        foreach (var engineDataProp in entity.EngineDataProperty)
                        {
                            engineDataProp.Create();
                            engineDataProp.EngineDataID = engineDataID;
                            if (string.IsNullOrEmpty(caseID))
                            {
                                engineDataProp.CaseID = "0";
                            }
                            else
                            {
                                engineDataProp.CaseID = caseID;
                            }
                            //engineDataProp.CaseID = "0";//创建时，写入到默认case
                        }
                        Db.Insertable(entity.EngineDataProperty).AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        #endregion

                        #region 新增属性（其他的所有case，值用默认值）
                        foreach (var caseEntity in cases.Where(x => x.CaseID != caseID))
                        {
                            //把objectTypep里的一套，和默认值带过来即可
                            var enginedataProps = new List<ec_enginedata_propertyEntity>();
                            Db.Queryable<ec_propertyEntity>().AS(propertyTableName)
                                .InnerJoin<ec_objecttypepEntity>((a, b) => a.PropertyID == b.PropertyID)//&& !string.IsNullOrEmpty(a.DefaultValue)
                                .AS<ec_objecttypepEntity>(objectTypepTableName)
                                .InnerJoin<ec_objecttypeEntity>((a, b, c) => b.ObjectTypeID == c.ObjectTypeID && c.ObjectTypeID == entity.ObjectTypeID)
                                .AS<ec_objecttypeEntity>(objectTypeTableName)
                                .LeftJoin<ec_measuring_unitEntity>((a, b, c, d) => a.DefaultUnit == d.MeasuringUnitID)
                                .AS<ec_measuring_unitEntity>(unitTableName)
                                .Select((a, b, c, d) => new { a, d })
                                .ToList().ForEach(x =>
                                {
                                    var enginedataProp = new ec_enginedata_propertyEntity()
                                    {
                                        EngineDataID = engineDataID,
                                        PropertyName = x.a.PropertyName,
                                        PropertyValue = x.a.DefaultValue,
                                        MeasuringUnit = x.d.MeasuringUnitName,
                                        CaseID = caseEntity.CaseID,
                                    };
                                    enginedataProp.Create();
                                    enginedataProps.Add(enginedataProp);
                                });
                            Db.Insertable(enginedataProps).AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").ExecuteCommand(); //231007
                        }
                        #endregion
                        #region 新增ec panel的记录（除了电缆）
                        var objectType = new ec_objecttypeBLL().GetEntity(addEnginedata.ObjectTypeID, projectId);
                        if (objectType != null && !objectType.ObjectTypeName.EndsWith("电缆"))
                        {

                            var ec_panel = new ec_PanelBLL();
                            var newPanel = new ec_PanelEntity();
                            newPanel.Create();
                            newPanel.EngineerDataID = addEnginedata.EngineDataID;

                            ec_panel.SaveEntity(projectId, "", newPanel);
                        }
                        #endregion
                    }


                    #region 根据传过来的图元集合
                    if (entity.EngineDataPixel == null)
                    {
                        entity.EngineDataPixel = new List<ec_enginedata_pixelEntity>();
                    }
                    foreach (var pixel in entity.EngineDataPixel)//修改时选中的那个pixel
                    {
                        var existPixel = Db.Queryable<ec_enginedata_pixelEntity>().AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").
                            First(x => x.DrawingFileID == pixel.DrawingFileID && x.PixelCode == pixel.PixelCode);
                        if (existPixel != null)
                        {
                            existPixel.Modify(existPixel.EngineDataPixelID);
                            existPixel.DeleteFlg = 0;
                            existPixel.EngineDataID = engineDataID;
                            existPixel.LibraryFileID = pixel.LibraryFileID;
                            existPixel.MaxPointX = pixel.MaxPointX;
                            existPixel.MinPointX = pixel.MinPointX;
                            existPixel.MaxPointY = pixel.MaxPointY;
                            existPixel.MinPointY = pixel.MinPointY;
                            Db.Updateable(existPixel).AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        }
                        else
                        {
                            pixel.Create();
                            pixel.DeleteFlg = 0;
                            pixel.EngineDataID = engineDataID;
                            Db.Insertable(pixel).AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        }
                        //SqlSugarHelper.Db.Ado.ExecuteCommand($" DELETE FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} WHERE DrawingFileID = '{pixel.DrawingFileID}' AND PixelCode = '{pixel.PixelCode}';");

                    }

                    //db.InsertByNoMap(entity.EngineDataPixel, $"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}");

                    #endregion
                }



                #region 电缆规格
                //更新电缆规格
                //var cableTableName = ProjectSugar.TableName<ec_CableEntity>(projectId);
                //var enginedataTableName = ProjectSugar.TableName<ec_enginedataEntity>(projectId);
                //var enginedataPropertyTableName = ProjectSugar.TableName<ec_enginedata_propertyEntity>(projectId);
                //var cableFormat = SqlSugarHelper.Db.Queryable<ec_CableEntity>().AS<ec_CableEntity>(cableTableName)
                //    .InnerJoin<ec_enginedata_propertyEntity>((a, b) => a.EngineerDataID == b.EngineDataID).AS<ec_enginedata_propertyEntity>(enginedataPropertyTableName)
                //    .InnerJoin<ec_enginedataEntity>((a, b, c) => b.EngineDataID == c.EngineDataID).AS<ec_enginedataEntity>(enginedataTableName)
                //    .Where((a, b, c) => b.PropertyName == "电缆规格" && b.CaseID == caseID && c.TagNumber == entity.TagNumber)
                //    .Select((a, b, c) => new { a, b })
                //    .First();
                //if (cableFormat != null)
                //{
                //    var cableID = cableFormat.a.CableID;
                //    var start = cableFormat.b.PropertyValue.Split('*', 'x', 'X', '✖');
                //    if (start.Length >= 2)
                //    {
                //        int setCount;
                //        int wireCount;
                //        var b1 = int.TryParse(start[0], out setCount);
                //        var b2 = int.TryParse(start[1], out wireCount);
                //        if (b1 && b2)
                //        {
                //            var cableSetTableName = ProjectSugar.TableName<ec_CableSetEntity>(projectId);
                //            var cableSetWireTableName = ProjectSugar.TableName<ec_CableSetWireEntity>(projectId);
                //            var sets = SqlSugarHelper.Db.Queryable<ec_CableSetEntity>().AS(cableSetTableName).Where(x => x.CableID == cableID).ToList();
                //            var wires = SqlSugarHelper.Db.Queryable<ec_CableSetWireEntity>().AS(cableSetWireTableName).Where(x => sets.Select(Y => Y.CableSetID).Contains(x.CableSetID)).ToList();
                //            var setMax = Math.Max(setCount, sets.Count);
                //            var insSets = new List<ec_CableSetEntity>();
                //            var insWires = new List<ec_CableSetWireEntity>();
                //            var delSets = new List<ec_CableSetEntity>();
                //            var delWires = new List<ec_CableSetWireEntity>();
                //            for (int i = 0; i < setMax; i++)
                //            {
                //                var set = new ec_CableSetEntity();
                //                if (i <= setCount - 1 && i <= sets.Count - 1)
                //                {
                //                    set = sets[i];
                //                }
                //                if (i > setCount - 1)
                //                {
                //                    var delSet = sets[i];
                //                    delSets.Add(delSet);
                //                    delWires.AddRange(wires.Where(x => x.CableSetID == delSet.CableSetID).ToList());
                //                }
                //                if (i > sets.Count - 1)
                //                {
                //                    set = new ec_CableSetEntity()
                //                    {
                //                        CableID = cableID,
                //                        CableSetSeq = i + 1,
                //                        CableSetName = $"Set{i + 1}",
                //                    };
                //                    set.Create();
                //                    insSets.Add(set);
                //                }
                //                if (!string.IsNullOrEmpty(set.CableSetID))
                //                {
                //                    var setWires = wires.Where(x => x.CableSetID == set.CableSetID).ToList();
                //                    var wireMax = Math.Max(wireCount, setWires.Count);
                //                    for (int j = 0; j < wireMax; j++)
                //                    {
                //                        if (j > wireCount - 1)
                //                        {
                //                            var delWire = setWires[j];
                //                            delWires.Add(delWire);
                //                        }
                //                        if (j > setWires.Count - 1)
                //                        {
                //                            var wire = new ec_CableSetWireEntity()
                //                            {
                //                                //CableID = cableID,
                //                                CableSetID = set.CableSetID,
                //                                SetLevel = j,
                //                                Wire_Tag = $"W{j + 1}"
                //                            };
                //                            wire.Create();
                //                            insWires.Add(wire);
                //                        }
                //                    }
                //                }
                //            }
                //            SqlSugarHelper.Db.Insertable(insSets).AS(cableSetTableName).ExecuteCommand();
                //            SqlSugarHelper.Db.Insertable(insWires).AS(cableSetWireTableName).ExecuteCommand();
                //            SqlSugarHelper.Db.Deleteable(delWires).AS(cableSetWireTableName).ExecuteCommand();
                //            SqlSugarHelper.Db.Deleteable(delSets).AS(cableSetTableName).ExecuteCommand();
                //        }
                //    }
                //}
                #endregion
                Db.CommitTran();
            }
            catch (Exception ex)
            {
                Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 更新工程数据属性默认值
        /// </summary>
        public void UpdateEngineDataByDefaultValue()
        {
            try
            {
                ec_enginedataService.UpdateEngineDataByDefaultValue();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        #endregion
        /// <summary>
        /// 验证字符串是否为整数
        /// </summary>
        /// <param name="value">要验证的字符串</param>    
        public static bool IsInteger(string value)
        {
            //如果为空，认为验证不合格
            if (string.IsNullOrEmpty(value))
            {
                return false;
            }
            return System.Text.RegularExpressions.Regex.IsMatch(value, @"^\d*$");
        }



        //cable - set - wire，4x3x1.5（电缆规格）
        //4个set，12个wire
        //用户给一个新的电缆规格，去同步实体（set和wire），给出要删哪些，要新增哪些，要修改哪些。
        void SyncCableSpec(string projId, string EngineDataId, string NewSpec, string OldSpec)
        {
            NewSpec = NewSpec.Replace("X", "x").Replace("x", "*");//都换为*
            OldSpec = OldSpec.Replace("X", "x").Replace("x", "*");//都换为*
            var Spec = NewSpec.Split('*');
            var Spec2 = OldSpec.Split('*');
            int setCount = 0;
            int wireCountPerSet = 0;
            int setCount2 = 0;
            int wireCountPerSet2 = 0;
            if (Spec.Length == 3)
            {
                int.TryParse(Spec[0], out setCount);
                int.TryParse(Spec[1], out wireCountPerSet);
            }
            else if (Spec.Length == 2)
            {
                setCount = 1;
                int.TryParse(Spec[0], out wireCountPerSet);
            }
            else
            {
                //格式不对
                return;
            }
            if (Spec2.Length == 3)
            {
                int.TryParse(Spec2[0], out setCount2);
                int.TryParse(Spec2[1], out wireCountPerSet2);
            }
            else if (Spec2.Length == 2)
            {
                setCount = 1;
                int.TryParse(Spec2[0], out wireCountPerSet2);
            }
            else
            {
                //格式不对
                return;
            }
            if (Spec.Length != Spec2.Length)
            {
                //暂不支持，比如3x1.5和3x2x1.5
                return;
            }
            if (setCount < 1 || wireCountPerSet < 1)
            {
                //格式不对
                return;
            }
            else
            {
                var cableServ = new ec_CableService();
                var projServ = new ec_projectService();
                var proj = projServ.GetEntity(projId);
                if (proj == null)
                {
                    return;
                }
                var existCable = cableServ.GetEntity(projId, EngineDataId);
                if (existCable != null)
                {
                    var cableSetServ = new ec_CableSetService();
                    var wireServ = new ec_CableSetWireService();
                    var wtServ = new ec_WireTerminalService();
                    existCable.Sets = cableSetServ.GetList(projId, existCable.CableID).ToList();
                    var existWires = wireServ.GetList(projId, existCable.CableID, "");
                    foreach (var s in existCable.Sets)
                    {
                        s.Wires = existWires.Where(X => X.CableSetID == s.CableSetID).ToList();
                    }

                    #region mengzhen
                    var SetWillCreate = new List<ec_CableSetEntity>();
                    var WireWillCreate = new List<ec_CableSetWireEntity>();
                    var SetWillRemove = new List<ec_CableSetEntity>();
                    var WireWillRemove = new List<ec_CableSetWireEntity>();
                    // 检查是否需要增加set
                    if (existCable.Sets.Count() < setCount)//比如 6 和 8 
                    {
                        //对之前的wire做判断，如果多了，那就减少，如果少了那就增加。写到外面去了
                        for (int i = existCable.Sets.Count(); i < setCount; i++)// 6 7 
                        {
                            var newSet = new ec_CableSetEntity();
                            newSet.Create();
                            newSet.CableSetName = $"Set{i + 1}";
                            newSet.CableID = existCable.CableID;
                            newSet.CableSetSeq = i + 1;
                            SetWillCreate.Add(newSet);
                            // 为新set添加指定数量的wire
                            for (int j = 0; j < wireCountPerSet; j++)
                            {
                                var newWire = new ec_CableSetWireEntity(newSet.CableSetID);
                                newWire.Wire_Tag = $"W{j + 1}";
                                newWire.SetLevel = j + 1;
                                WireWillCreate.Add(newWire);
                                Console.WriteLine($"将要创建wire: {newWire.WireID}, 属于set: {newSet.CableSetID}");
                            }
                        }
                    }
                    // 检查是否需要删除set
                    else if (existCable.Sets.Count() > setCount)//比如 6 和 4
                    {
                        // 更新现有的每个set中的wire数量写在外面了，当然写在里面逻辑清晰
                        var setsToRemove = existCable.Sets.Skip(setCount).ToList();
                        foreach (var set in setsToRemove)
                        {
                            SetWillRemove.Add(set);
                            Console.WriteLine($"将要删除set: {set.CableSetID}");

                            // 将该set中的所有wire标记为删除
                            foreach (var wire in set.Wires)
                            {
                                WireWillRemove.Add(wire);
                                Console.WriteLine($"将要删除wire: {wire.WireID}, 属于set: {set.CableSetID}");
                            }

                            existCable.Sets.Remove(set);
                        }

                    }

                    // 更新现有的每个set中的wire数量，把三种情况的每个set中的wire数量都更新掉
                    foreach (var set in existCable.Sets)
                    {
                        if (set.Wires.Count > wireCountPerSet)//老的多，需要删
                        {
                            var wiresToRemove = set.Wires.Skip(wireCountPerSet).ToList();
                            foreach (var wire in wiresToRemove)
                            {
                                WireWillRemove.Add(wire);
                                Console.WriteLine($"将要删除wire: {wire.WireID}, 属于set: {set.CableSetID}");
                            }
                        }
                        else if (set.Wires.Count < wireCountPerSet)//老的少，需要增
                        {
                            for (int j = set.Wires.Count; j < wireCountPerSet; j++)
                            {
                                var newWire = new ec_CableSetWireEntity(set.CableSetID);
                                newWire.Wire_Tag = $"W{j + 1}";
                                newWire.SetLevel = j + 1;
                                WireWillCreate.Add(newWire);
                                Console.WriteLine($"将要创建wire: {newWire.WireID}, 属于set: {set.CableSetID}");
                            }
                        }
                    }
                    #endregion
                    Db.Insertable(SetWillCreate).AS($"ec_cable_set_{proj.ProjectIndex}").ExecuteCommand();
                    Db.Insertable(WireWillCreate).AS($"ec_cable_set_wire_{proj.ProjectIndex}").ExecuteCommand();
                    Db.Deleteable(SetWillRemove).AS($"ec_cable_set_{proj.ProjectIndex}").ExecuteCommand();
                    Db.Deleteable(WireWillRemove).AS($"ec_cable_set_wire_{proj.ProjectIndex}").ExecuteCommand();
                    var allConns = wtServ.GetList("{ProjectId:\"" + projId + "\",CableID:\"" + existCable.CableID + "\"}").ToList();
                    try
                    {
                        var ConnsWillRemove = allConns.Where(x => WireWillRemove.Select(y => y.WireID).Contains(x.WireID)).ToList();
                        Db.Deleteable(ConnsWillRemove).AS($"ec_Wire_Terminal_{proj.ProjectIndex}").ExecuteCommand();
                    }
                    catch (Exception)
                    {

                    }

                }
                else
                {
                    return;
                }
            }



            //if (newSetNum == 0)
            //{
            //    foreach (var wire in existCable.Wires)
            //    {
            //        Console.WriteLine($"  线 ID: {wire.WireID}, 标签: {wire.Wire_Tag}, 层级: {wire.SetLevel}");
            //    }
            //}
            //else
            //{
            //    foreach (var set in existCable.Sets)
            //    {
            //        Console.WriteLine($"集合 ID: {set.CableSetID}, 集合名称: {set.CableSetName}");

            //        // 遍历该集合中的所有线
            //        foreach (var wire in set.Wires)
            //        {
            //            Console.WriteLine($"  线 ID: {wire.WireID}, 属于集合: {set.CableSetID}, 标签: {wire.Wire_Tag}, 层级: {wire.SetLevel}");
            //        }
            //    }
            //}
            //Console.WriteLine("test");




            //var SetWillCreate = new List<ec_CableSetEntity>();
            //var WireWillCreate = new List<ec_CableSetWireEntity>();
            //var SetWillRemove = new List<ec_CableSetEntity>();
            //var WireWillRemove = new List<ec_CableSetWireEntity>();
            //var CableWireWillCreate = new List<ec_CableWireEntity>();
            //var CableWireWillRemove = new List<ec_CableWireEntity>();

            //// 检查set是否为0
            //if (newSetNum == 0)
            //{
            //    //检查existcableset是否为零
            //    if (existCable.Sets.Count == 0)
            //    {
            //        if (existCable.Wires.Count <= newWireNumPerSet)
            //        {
            //            for (int j = existCable.Wires.Count; j < newWireNumPerSet; j++)
            //            {
            //                var newWire = new ec_CableWireEntity(existCable.CableID);
            //                newWire.Wire_Tag = $"W{j + 1}";
            //                newWire.SetLevel = j + 1;
            //                CableWireWillCreate.Add(newWire);
            //                Console.WriteLine($"将要创建Wire: {newWire.WireID}");
            //            }
            //        }
            //        else if (existCable.Wires.Count > newWireNumPerSet)
            //        {
            //            for (int j = existCable.Wires.Count - 1; j >= newWireNumPerSet; j--)
            //            {
            //                var wireToRemove = existCable.Wires[j];//现在还没有写具体的要怎么移除
            //                CableWireWillRemove.Add(wireToRemove);
            //                Console.WriteLine($"将要删除Wire: {wireToRemove.WireID}");
            //            }
            //        }
            //        foreach (var newWire in CableWireWillCreate)
            //        {
            //            existCable.Wires.Add(newWire);
            //            Console.WriteLine($"创建并添加了直接关联的Wire: {newWire.WireID} 到电缆");
            //        }
            //        foreach (var wireToRemove in CableWireWillRemove)
            //        {
            //            if (existCable.Wires.Remove(wireToRemove))
            //            {
            //                Console.WriteLine($"从电缆移除了直接关联的Wire: {wireToRemove.WireID}");
            //            }
            //        }
            //    }
            //    else//现在讨论a*b》0*8，删除所有wire，重新跑一下var existCable = new ec_CableEntity("test1", 0, 3);//如果不等于0，但是之前的是0x8，是否要讨论 就是从0*8》4*4
            //    {
            //        // 删除所有set直接关联的wire
            //        SetWillRemove.AddRange(existCable.Sets);//这个时候把所有被移除的set放里面了，要再来一个语句把wire放进去吗？我没放，因为set里面本身就包含了wire的信息
            //                                                //foreach (var setToRemove in SetWillRemove)
            //                                                //{
            //                                                //    // 添加该集合下的所有wire到 WireWillRemove 列表
            //                                                //    foreach (var wire in setToRemove.Wires)
            //                                                //    {
            //                                                //        WireWillRemove.Add(wire);
            //                                                //    }
            //                                                //}
            //        existCable.Sets.Clear();
            //        Console.WriteLine("删除了所有set直接关联的wire");

            //        // 创建新的wire
            //        for (int i = 0; i < newWireNumPerSet; i++)
            //        {
            //            var wires = new ec_CableWireEntity(existCable.CableID);
            //            wires.WireID = Guid.NewGuid().ToString();
            //            wires.SetLevel = i + 1;
            //            wires.Wire_Tag = "W" + (i + 1).ToString();
            //            CableWireWillCreate.Add(wires);
            //        }
            //        foreach (var newWire in CableWireWillCreate)
            //        {
            //            existCable.Wires.Add(newWire);
            //            Console.WriteLine($"创建并添加了直接关联的Wire: {newWire.WireID} 到电缆");
            //        }


            //    }
            //}
            //else
            //{
            //    if (existCable.Sets.Count == 0)
            //    {
            //        CableWireWillRemove.AddRange(existCable.Wires);
            //        existCable.Wires.Clear();
            //        for (int i = 0; i < newSetNum; i++)
            //        {
            //            var SetEntity = new ec_CableSetEntity(existCable.CableID);
            //            //SetEntity.CableSetID = Guid.NewGuid().ToString();在ec_CableSetEntity中已经对CableSetID定义了值
            //            SetEntity.CableSetSeq = i + 1;
            //            SetEntity.CableSetName = "Set" + (i + 1).ToString();

            //            for (int j = 0; j < newWireNumPerSet; j++)
            //            {
            //                var WireEntity = new ec_CableSetWireEntity(SetEntity.CableSetID);
            //                //WireEntity.WireID = Guid.NewGuid().ToString();在ec_CableSetWireEntity已经对WireID定义了值
            //                WireEntity.SetLevel = j + 1;
            //                WireEntity.Wire_Tag = "W" + (j + 1).ToString();
            //                SetEntity.Wires.Add(WireEntity);
            //            }
            //            SetWillCreate.Add(SetEntity);
            //        }
            //        foreach (var setToRemove in SetWillCreate)
            //        {
            //            foreach (var wire in setToRemove.Wires)
            //            {
            //                WireWillCreate.Add(wire);
            //            }
            //        }
            //        //将这些set、wire放到existcable中
            //        foreach (var set in SetWillCreate)
            //        {
            //            existCable.Sets.Add(set);
            //        }

            //    }
            //    else
            //    {
            //        // 检查是否需要增加set
            //        if (existCable.Sets.Count < newSetNum)
            //        {
            //            //对之前的wire做判断，如果多了，那就减少，如果少了那就增加。写到外面去了

            //            for (int i = existCable.Sets.Count; i < newSetNum; i++)
            //            {
            //                var newSet = new ec_CableSetEntity(existCable.CableID);
            //                newSet.CableSetName = $"Set {i + 1}";
            //                newSet.CableSetSeq = i + 1;
            //                SetWillCreate.Add(newSet);
            //                Console.WriteLine($"将要创建set: {newSet.CableSetID}");

            //                // 为新set添加指定数量的wire
            //                for (int j = 0; j < newWireNumPerSet; j++)
            //                {
            //                    var newWire = new ec_CableSetWireEntity(newSet.CableSetID);
            //                    newWire.Wire_Tag = $"W{j + 1}";
            //                    newWire.SetLevel = j + 1;
            //                    WireWillCreate.Add(newWire);
            //                    Console.WriteLine($"将要创建wire: {newWire.WireID}, 属于set: {newSet.CableSetID}");
            //                }
            //            }
            //        }

            //        // 检查是否需要删除set
            //        else if (existCable.Sets.Count > newSetNum)
            //        {
            //            // 更新现有的每个set中的wire数量写在外面了，当然写在里面逻辑清晰

            //            var setsToRemove = existCable.Sets.Skip(newSetNum).ToList();
            //            foreach (var set in setsToRemove)
            //            {
            //                SetWillRemove.Add(set);
            //                Console.WriteLine($"将要删除set: {set.CableSetID}");

            //                // 将该set中的所有wire标记为删除
            //                foreach (var wire in set.Wires)
            //                {
            //                    WireWillRemove.Add(wire);
            //                    Console.WriteLine($"将要删除wire: {wire.WireID}, 属于set: {set.CableSetID}");
            //                }
            //            }
            //        }

            //        // 更新现有的每个set中的wire数量，把三种情况的每个set中的wire数量都更新掉
            //        foreach (var set in existCable.Sets)
            //        {
            //            if (set.Wires.Count > newWireNumPerSet)
            //            {
            //                var wiresToRemove = set.Wires.Skip(newWireNumPerSet).ToList();
            //                foreach (var wire in wiresToRemove)
            //                {
            //                    WireWillRemove.Add(wire);
            //                    Console.WriteLine($"将要删除wire: {wire.WireID}, 属于set: {set.CableSetID}");
            //                }
            //            }
            //            else if (set.Wires.Count < newWireNumPerSet)
            //            {
            //                for (int j = set.Wires.Count; j < newWireNumPerSet; j++)
            //                {
            //                    var newWire = new ec_CableSetWireEntity(set.CableSetID);
            //                    newWire.Wire_Tag = $"W{j + 1}";
            //                    newWire.SetLevel = j + 1;
            //                    WireWillCreate.Add(newWire);
            //                    Console.WriteLine($"将要创建wire: {newWire.WireID}, 属于set: {set.CableSetID}");
            //                }
            //            }
            //        }

            //        foreach (var set in SetWillRemove)
            //        {
            //            existCable.Sets.Remove(set);
            //        }
            //        foreach (var set in SetWillCreate)
            //        {
            //            var wiresForSet = WireWillCreate.Where(wire => wire.CableSetID == set.CableSetID).ToList();//在前面还是要把WireWillCreate写出来

            //            // 为当前 Set 的 Wires 集合添加这些 Wire 对象
            //            foreach (var wire in wiresForSet)
            //            {
            //                set.Wires.Add(wire);
            //            }

            //            // 最后，将 Set（现在已经包含 Wire 对象）添加到 existCable.Sets 集合中
            //            existCable.Sets.Add(set);
            //        }
            //        foreach (var wireToRemove in WireWillRemove)
            //        {
            //            var set = existCable.Sets.FirstOrDefault(s => s.CableSetID == wireToRemove.CableSetID);
            //            if (set != null)
            //            {
            //                set.Wires.Remove(wireToRemove);
            //            }
            //        }
            //        foreach (var newWire in WireWillCreate)
            //        {
            //            // 找到这个新 Wire 应该属于的 Set
            //            var targetSet = existCable.Sets.FirstOrDefault(s => s.CableSetID == newWire.CableSetID);

            //            if (targetSet != null)
            //            {
            //                // 将新 Wire 添加到找到的 Set 的 Wires 集合中
            //                targetSet.Wires.Add(newWire);
            //            }
            //        }
            //    }

            //}

            //Console.WriteLine("最终的电缆配置：");
            //// 遍历所有集合

            //if (newSetNum == 0)
            //{
            //    foreach (var wire in existCable.Wires)
            //    {
            //        Console.WriteLine($"  线 ID: {wire.WireID}, 标签: {wire.Wire_Tag}, 层级: {wire.SetLevel}");
            //    }
            //}
            //else
            //{
            //    foreach (var set in existCable.Sets)
            //    {
            //        Console.WriteLine($"集合 ID: {set.CableSetID}, 集合名称: {set.CableSetName}");

            //        // 遍历该集合中的所有线
            //        foreach (var wire in set.Wires)
            //        {
            //            Console.WriteLine($"  线 ID: {wire.WireID}, 属于集合: {set.CableSetID}, 标签: {wire.Wire_Tag}, 层级: {wire.SetLevel}");
            //        }
            //    }
            //}
            //Console.WriteLine("test");
        }

    }
}
